import sys
from datetime import date

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication

from view.components.ui_dateRangePicker import Ui_DateRangePicker


class DateRangePicker(QWidget, Ui_DateRangePicker):
    # 数据发生改变时发送信号
    changed = pyqtSignal(list)
    _FORMAT_STRING = '{}-{:0>2d}-{:0>2d}'

    def __init__(self, parent=None, dateRange=None):
        super().__init__(parent)
        self.setupUi(self)

        if not dateRange:
            dateRange = [date.today(), date.today()]
        self.editBegin.setDate(dateRange[0])
        self.editEnd.setDate(dateRange[1])
        self.editBegin.dateChanged.connect(lambda: self.onChange())
        self.editEnd.dateChanged.connect(lambda: self.onChange())

    def onChange(self):
        """
        数据发生改变时发送changed信号
        :return:
        """
        data = self.getDateRange()
        self.changed.emit(data)

    def getDateRange(self):
        """
        返回当前选择的日期范围
        :return:
        """
        return [
            self._FORMAT_STRING.format(*self.editBegin.date().getDate()),
            self._FORMAT_STRING.format(*self.editEnd.date().getDate())
        ]


if __name__ == '__main__':
    app = QApplication(sys.argv)  # 创建GUI应用程序
    widget = DateRangePicker()  # 创建窗体
    widget.changed.connect(print)
    widget.show()
    sys.exit(app.exec_())
